﻿
using System.Windows;
using System.Windows.Media;

namespace Cyl.ImageControl;

public class RectangleROI : ROI
{
    public override void Draw(DrawingContext dc, double scale, Point offset)
    {
        ApplyTransform(dc, scale, offset);
        dc.DrawRectangle(null, new Pen(new SolidColorBrush(Color), 2), Bounds);
        dc.Pop();
    }

    public override Point[] GetControlPoints()
    {
        return new Point[]
        {
                new Point(Bounds.Left, Bounds.Top),
                new Point(Bounds.Right, Bounds.Top),
                new Point(Bounds.Left, Bounds.Bottom),
                new Point(Bounds.Right, Bounds.Bottom)
        };
    }

    public override void UpdateControlPoint(Point controlPoint, Point newPosition)
    {
        var offsetX = newPosition.X - controlPoint.X;
        var offsetY = newPosition.Y - controlPoint.Y;

        if (controlPoint == new Point(Bounds.Left, Bounds.Top))
        {
            var newLeft = Math.Min(Bounds.Left + offsetX, Bounds.Right);
            var newTop = Math.Min(Bounds.Top + offsetY, Bounds.Bottom);
            Bounds = new Rect(newLeft, newTop, Bounds.Right - newLeft, Bounds.Bottom - newTop);
        }
        else if (controlPoint == new Point(Bounds.Right, Bounds.Top))
        {
            var newRight = Math.Max(Bounds.Left, Bounds.Right + offsetX);
            var newTop = Math.Min(Bounds.Top + offsetY, Bounds.Bottom);
            Bounds = new Rect(Bounds.Left, newTop, newRight - Bounds.Left, Bounds.Bottom - newTop);
        }
        else if (controlPoint == new Point(Bounds.Left, Bounds.Bottom))
        {
            var newLeft = Math.Min(Bounds.Left + offsetX, Bounds.Right);
            var newBottom = Math.Max(Bounds.Top, Bounds.Bottom + offsetY);
            Bounds = new Rect(newLeft, Bounds.Top, Bounds.Right - newLeft, newBottom - Bounds.Top);
        }
        else if (controlPoint == new Point(Bounds.Right, Bounds.Bottom))
        {
            var newRight = Math.Max(Bounds.Left, Bounds.Right + offsetX);
            var newBottom = Math.Max(Bounds.Top, Bounds.Bottom + offsetY);
            Bounds = new Rect(Bounds.Left, Bounds.Top, newRight - Bounds.Left, newBottom - Bounds.Top);
        }
    }

    public override void Move(Point offset)
    {
        Bounds = new Rect(new Point(Bounds.X + offset.X, Bounds.Y + offset.Y), Bounds.Size);
    }
}
